package com.xbang.attendance.web.action.system.treport;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.springframework.beans.factory.annotation.Autowired;

import com.demo2do.lighturl.annotation.Action;
import com.xbang.attendance.entity.treport.Treport;
import com.xbang.attendance.service.PurchaseOrderService;
import com.xbang.core.page.Result;
import com.xbang.core.struts.support.SearchActionSupport;

/**
 * @author dev.zhang
 * 
 */
public class Index extends SearchActionSupport {

	private static final long serialVersionUID = 6137752167041062321L;

	private static final Log logger = LogFactory.getLog(Index.class);

	private static final String Mintime = null;

	@Autowired
	private PurchaseOrderService purchaseOrderService;

	private List<Treport> treport;
	
	private Integer id;

	@Action("/system/treport/index/${currPageId}")
	public String listByPage() throws Exception {

		return list();
	}
	//年
	private List yearList=new ArrayList();
	public List getYearList() {
		return yearList;
	}

	public void setYearList(List yearList) {
		this.yearList = yearList;
	}
	//季度
	private List jiduList=new ArrayList();
	public List getJiduList() {
		return jiduList;
	}

	public void setJiduList(List jiduList) {
		this.jiduList = jiduList;
	}
	//月
	private List monthList=new ArrayList();
	
	public List getMonthList() {
		return monthList;
	}

	public void setMonthList(List monthList) {
		this.monthList = monthList;
	}

	//初始化数据
	public void init(){
		//获取当前时间
		Calendar cal = Calendar.getInstance();
//		int day = cal.get(Calendar.DATE);
//		int month = cal.get(Calendar.MONTH) + 1;
		int year = cal.get(Calendar.YEAR);
		yearList.add("");
		for(int i=year;i>=(year-5);i--){
			yearList.add(i);
		}
		monthList.add("");
		for(int i=1;i<=12;i++){
			monthList.add(i);
		}
	}
	private String time;
	
	public String getTime() {
		return time;
	}

	public void setTime(String time) {
		this.time = time;
	}
	private String startTime;
	private String endTime;
	
	
	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public void initFilter(String s) throws Exception{
		Treport treport1 = null;
		int s2 =Integer.parseInt(s.subSequence(5,7).toString());
		String s1 ="%"+ s.substring(0,7)+"%";
		//现在的月份
		int  m= Integer.parseInt(s.subSequence(5,7).toString());
		//现在的年份
		int y = Integer.parseInt(s.subSequence(0, 4).toString());
		//更新数据之前treport表中的最大年份
		String sql7 = "select year from treport order by year desc LIMIT 1";
		List<Map> list9 = purchaseOrderService.queryForList(sql7, map);
		//更新数据之前detail表中的最大日期
		String sqlp = "select date from detail order by date asc LIMIT 1";
		 List<Map> p= purchaseOrderService.queryForList(sqlp, map);
		 Map map0 = p.get(0);
		 
		int n=Integer.valueOf(map0.get("date").toString().substring(5, 7).toString()) ;
		int k = Integer.valueOf(map0.get("date").toString().substring(0,4).toString());
		if(!list9.isEmpty()){
			k = purchaseOrderService.queryForInt(sql7, map);
		//更新数据之前treport表中的最大月份
		String sql = "select month from treport where year = "+k+" order by month desc LIMIT 1";
		 n = purchaseOrderService.queryForInt(sql, map);
		String sqL1= "delete from treport where month="+n+" and year = "+k;
		purchaseOrderService.execute(sqL1,map);
		}
		while(k<y){
			while(n<=12){
				String s0 = null; 
				if(n<10){
					s0 = k+"-0"+n;
				}else{
				 s0 = k+"-"+n;
				}
				String s9 = "%"+s0+"%";
				String hqlSentence3 = "select * FROM detail where date like '"+s9+"' group by user_name ";
				List<Map> list2 = purchaseOrderService.queryForList(hqlSentence3, map);
				if(!list2.isEmpty()){
				for(Map map1:list2){
					 treport1 = new Treport();
						String name =  map1.get("user_name").toString();
						if(map1.get("date").toString().contains(s0)){
							String hql1 = "select count(*) from detail where user_name='" +name +"' and lateor='1'and date like'"+s9+"'";
							treport1.setLatecount(purchaseOrderService.queryForInt(hql1, map));
							String hql2 = "select count(*) from detail where user_name='" +name+"' and TYPE='请假'and date like '"+s9+"'";
							treport1.setLeavecount(purchaseOrderService.queryForInt(hql2, map));
							String hql3 = "select count(*) from detail where user_name='" +name+"' and TYPE='公司签到'and date like '"+s9+"'";
							treport1.setComcount(purchaseOrderService.queryForInt(hql3, map));
							String hql4 = "select count(*) from detail where user_name='" +name+"' and TYPE='外勤签到'and date like '"+s9+"'";
							treport1.setOutcount(purchaseOrderService.queryForInt(hql4, map));
							treport1.setAttendancecount(purchaseOrderService.queryForInt(hql3, map)+purchaseOrderService.queryForInt(hql4, map));
							treport1.setDepartment(map1.get("department").toString());
							treport1.setUsername(name);
							m=Integer.parseInt(s9.subSequence(6,8).toString());
							int l = Integer.parseInt(s9.subSequence(1, 5).toString()); 
							treport1.setMonth(m);
							treport1.setYear(l);
								purchaseOrderService.save(treport1);
						}
				}
				}
				n=n+1;
				if(s2<10){
					s9="%"+s9.substring(0, 5)+"0"+n+"%";
				}else{
					s9="%"+s9.substring(0, 5)+n+"%";
				}
			}
			k=k+1;
			n=1;
		}
		if(m!=n){
				while(s2>=n){
					String hqlSentence3 = "select * FROM detail  where date like '"+s1+"' group by user_name";
					List<Map> list2 = purchaseOrderService.queryForList(hqlSentence, map);
					for(Map map1:list2){
						 treport1 = new Treport();
							String name =  map1.get("user_name").toString();
							 String s8 = s1.substring(1,8);
							if(map1.get("date").toString().contains(s8)){
								String hql1 = "select count(*) from detail where user_name='" +name +"' and lateor='1' and date like'"+s1+"'";
								treport1.setLatecount(purchaseOrderService.queryForInt(hql1, map));
								String hql2 = "select count(*) from detail where user_name='" +name+"' and TYPE='请假' and date like '"+s1+"'";
								treport1.setLeavecount(purchaseOrderService.queryForInt(hql2, map));
								String hql3 = "select count(*) from detail where user_name='" +name+"' and TYPE='公司签到' and date like '"+s1+"'";
								treport1.setComcount(purchaseOrderService.queryForInt(hql3, map));
								String hql4 = "select count(*) from detail where user_name='" +name+"' and TYPE='外勤签到'and date like '"+s1+"'";
								treport1.setOutcount(purchaseOrderService.queryForInt(hql4, map));
								treport1.setAttendancecount(purchaseOrderService.queryForInt(hql3, map)+purchaseOrderService.queryForInt(hql4, map));
								treport1.setDepartment(map1.get("department").toString());
								treport1.setUsername(name);
								m=Integer.parseInt(s8.subSequence(5,7).toString()); 
								int l = Integer.parseInt(s8.subSequence(0, 4).toString()); 
								treport1.setMonth(m);
								treport1.setYear(l);
								purchaseOrderService.save(treport1);
							}
					}
					s2=s2-1;
					if(s2<10){
						s1="%"+s.substring(0, 5)+"0"+s2+"%";
					}else{
						s1="%"+s.substring(0, 5)+s2+"%";
					}
				}
		}else{
			String hqlSentence2 = "select * FROM detail  where date like '"+s1+"' group by user_name";
			List<Map> list1 = purchaseOrderService.queryForList(hqlSentence2, map);
			for(Map map1:list1){
				 treport1 = new Treport();
				 String s7 = s1.substring(1,8);
				 if(map1.get("date").toString().contains(s7)){
					String name =  map1.get("user_name").toString();	
						String hql1 = "select count(*) from detail where user_name='" +name +"' and lateor='1'and date like '"+s1+"'";
						treport1.setLatecount(purchaseOrderService.queryForInt(hql1, map)); 
						String hql2 = "select count(*) from detail where user_name='" +name+"' and TYPE='请假'and date like '"+s1+"'";
						treport1.setLeavecount(purchaseOrderService.queryForInt(hql2, map));
						String hql3 = "select count(*) from detail where user_name='" +name+"' and TYPE='公司签到'and date like '"+s1+"'";
						treport1.setComcount(purchaseOrderService.queryForInt(hql3, map));
						String hql4 = "select count(*) from detail where user_name='" +name+"' and TYPE='外勤签到'and date like '"+s1+"'";
						treport1.setOutcount(purchaseOrderService.queryForInt(hql4, map));
						treport1.setAttendancecount(purchaseOrderService.queryForInt(hql3, map)+purchaseOrderService.queryForInt(hql4, map));
						
						treport1.setDepartment(String.valueOf(map1.get("department"))!=null?String.valueOf(map1.get("department")):"");
						
						treport1.setUsername(name);
						treport1.setMonth(m);
						treport1.setYear(y);
							purchaseOrderService.save(treport1);
				 }
			}
		}
	}
	private void initshuju(String startTime,String endTime) throws Exception{
		Treport treport1 = null;
		String hqlSentence3 = "select * FROM detail where date >='"+startTime+"' and date<='"+endTime+"' group by user_name ";
		List<Map> list2 = purchaseOrderService.queryForList(hqlSentence3, map);
		if(!list2.isEmpty()){
		for(Map map1:list2){
			 treport1 = new Treport();
				String name =  map1.get("user_name").toString();
					String hql1 = "select count(*) from detail where user_name='" +name +"' and lateor='1'and date >='"+startTime+"' and date<='"+endTime+"'";
					treport1.setLatecount(purchaseOrderService.queryForInt(hql1, map));
					String hql2 = "select count(*) from detail where user_name='" +name+"' and TYPE='请假'and date >='"+startTime+"' and date<='"+endTime+"'";
					treport1.setLeavecount(purchaseOrderService.queryForInt(hql2, map));
					String hql3 = "select count(*) from detail where user_name='" +name+"' and TYPE='公司签到'and date >='"+startTime+"' and date<='"+endTime+"'";
					treport1.setComcount(purchaseOrderService.queryForInt(hql3, map));
					String hql4 = "select count(*) from detail where user_name='" +name+"' and TYPE='外勤签到'and date >='"+startTime+"' and date<='"+endTime+"'";
					treport1.setOutcount(purchaseOrderService.queryForInt(hql4, map));
					//实际出勤天数
					String shql2="select * from detail where user_name='" +name+"' and (TYPE='公司签到' or type='外勤签到')and date >='"+startTime+"' and date<='"+endTime+"' GROUP BY date";
					List<Map> sjnumberList=purchaseOrderService.queryForList(shql2, map);
					treport1.setSjnumber(sjnumberList.size());
					//合计次数
					treport1.setAttendancecount(purchaseOrderService.queryForInt(hql3, map)+purchaseOrderService.queryForInt(hql4, map));
					treport1.setDepartment(map1.get("department").toString());
					String hql5="select sum(work_hour) from detail where user_name='" +name+"' and (TYPE='公司签到' or type='外勤签到')and date >='"+startTime+"' and date<='"+endTime+"'";
					treport1.setTimetotal(purchaseOrderService.queryForInt(hql5, map));
					treport1.setUsername(name);
					treport1.setStartname(startTime); 
					treport1.setEndname(endTime);
					//获取用户所对应的签到工作进度
					String sqlp = "select * from wtime where user='"+name+"'";
					List<Map> p= purchaseOrderService.queryForList(sqlp, map);
					if(p.size()>0 && p!=null){
						//应出勤天数
						String hql6="select month_limit_time from wtime where user='"+name+"'";
						treport1.setYnumber(purchaseOrderService.queryForInt(hql6, map));
						//迟到次数
						/*String hql7="select count(*) from detail where user_name='" +name+"' and (TYPE='公司签到' or type='外勤签到')and date >='"+startTime+"' and date<='"+endTime+"' and record_ontime>'"+p.get(0).get("startTime")+"'";
						treport1.setLatecount(purchaseOrderService.queryForInt(hql7, map));*/
						//满足条件的集合
						String shql1="select * from detail where user_name='" +name+"' and (TYPE='公司签到' or type='外勤签到')and date >='"+startTime+"' and date<='"+endTime+"'";
						List<Map> map2=purchaseOrderService.queryForList(shql1, map);
						int qscount=0;
						int qecount=0;
						//正常上班时间
						String ontime=p.get(0).get("start_time").toString();
						if(ontime.length()<=4){
							ontime="0"+ontime;
						}
						//正常下班时间
						String outtime=p.get(0).get("end_time").toString();
						if(outtime.length()<=4){
							outtime="0"+outtime;
						}
						for (Map map : map2) {
							String qstime=map.get("record_ontime").toString().substring(11,16);  //签到时间
							String qetime=map.get("record_outtime").toString().substring(11,16);  //签出时间
							if(qstime.compareTo(ontime)>0){
								qscount++;
							}
							if(outtime.compareTo(qetime)>0){
								qecount++;
							}
							/*if(Integer.parseInt(qstime.substring(0,2).toString())>=Integer.parseInt(ontime.substring(0,2))){
								if(Integer.parseInt(qstime.substring(0,2).toString())==Integer.parseInt(ontime.substring(0,2)) && Integer.parseInt(qstime.substring(3).toString())>=Integer.parseInt(ontime.substring(3))){
									qscount++;
								}								
							}
							if(Integer.parseInt(qetiem.substring(0,2).toString())<=Integer.parseInt(outtime.substring(0,2))){
								if(Integer.parseInt(qetiem.substring(0,2).toString())==Integer.parseInt(outtime.substring(0,2)) && Integer.parseInt(qetiem.substring(3).toString())<=Integer.parseInt(outtime.substring(3))){
									qecount++;
								}						
							}*/
						}
						//迟到次数
						treport1.setLatecount(qscount);
						//早退次数
						treport1.setZaotui(qecount);
						/*String hql8="select count(*) from detail where user_name='" +name+"' and (TYPE='公司签到' or type='外勤签到')and date >='"+startTime+"' and date<='"+endTime+"' and record_outtime>'"+p.get(0).get("endTime")+"'";
						treport1.setZaotui(purchaseOrderService.queryForInt(hql8, map));*/
					}
				    purchaseOrderService.save(treport1);
				}
		}
	}
	private Map map = new HashMap();
	private String hqlSentence = "select * FROM detail group by user_name ";
	private Date dateTime=new Date();
	@Action("/system/treport/list")
	public String list() throws Exception {
		//获取过滤的条件（年、月、季度）		
		String t1=this.getStartTime();
		String t2=this.getEndTime();
		//获取当前的月
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dtime=sdf.format(dateTime);
		int year=Integer.parseInt(dtime.substring(0, 4));   //年
		int month=Integer.parseInt(dtime.substring(5,7));    //月
		int day;
		if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
			day=31;
		}else if(month==4 || month==6 || month==9 || month==11){
			day=30;
		}else{
			if(year/4==0){
				day=29;
			}else{
				day=28;	
			}
		}
		
		String startTime=year+"-"+dtime.substring(5,7)+"-0"+1;
		String endTime=year+"-"+dtime.substring(5,7)+"-"+day;
		
		List<Map> list = purchaseOrderService.queryForList(hqlSentence, map);
		//判断签到明细里是否有数据，若没有则删除统计报表里的数据
		if(!list.isEmpty()){
			purchaseOrderService.execute("delete from treport",map);
			if(t1==null && t2==null){
//				purchaseOrderService.execute("delete from treport",map);
				//取detail表里所有年份
				String allYear="select date from detail group by date desc";
				/*List<Map> p= purchaseOrderService.queryForList(allYear, map);
				for (Map map : p) {
					if(map.get("date")==null){
						continue;
					}
					String date=map.get("date").toString().substring(0,7);
					
				}*/
				initshuju(startTime,endTime);
			}else{
				initshuju(t1,t2);
			}
		}
		
		/*init();
		List<Map> list = purchaseOrderService.queryForList(hqlSentence, map);
		String hqlSentence1 = null;
		//判断签到明细里是否有数据，若没有则删除统计报表里的数据
		if (!list.isEmpty()) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String s = null;
			//过滤（月度，季度，年度） 
			if(t!=null){
				int year=Integer.parseInt(t.substring(0, 4));   //年
				int month=Integer.parseInt(t.substring(4,6));    //月
				int jidu=Integer.parseInt(t.substring(6));    //季度:3－5月（春季） ;6－8月（夏季） ;9－11月（秋季）;12－2月（冬季）
				int jiduMonth1=0;
				int jiduMonth2=0;
				if(jidu>0){
					if(jidu>=3 && jidu<=5){
						jiduMonth1=3;
						jiduMonth2=5;
					}else if(jidu>=6 && jidu<=8){
						jiduMonth1=6;
						jiduMonth2=8;
					}else if(jidu>=9 && jidu<=11){
						jiduMonth1=9;
						jiduMonth2=11;
					}else if(jidu>=12 || jidu<=2){
						jiduMonth1=12;
						jiduMonth2=2;
					}
				}else{
					jiduMonth1=0;
					jiduMonth2=0;
				}
				
				if(year>0 && month>0 && jidu>0){
					s=year+"-"+month+"-";
				}
				hqlSentence1 = "FROM Treport treport WHERE 1=1 and year="+year+" and month="+month;
			}else{
				s = sdf.format(dateTime);
				initFilter(s);
				hqlSentence1 = "FROM Treport treport WHERE 1=1 ";
			}
			
			
		}
		*/
		String hqlSentence1 = "FROM Treport treport WHERE 1=1 ";
		if (searchComponent.getOrderParameters().isEmpty()) {
			searchComponent.addSearchElement("orderBy.treport.month", "DESC");
		}
		if (page != null) {
			if (currPageId.intValue() != -1 && currPageId.intValue() > 0) {
				page.setCurrentPage(currPageId);
			}
		}
		Result result = purchaseOrderService.searchByPage(hqlSentence1,
				searchComponent, page);
		treport = result.getItems();
		page = result.getPage();
		return "index";
	}

	@Action("/system/treport/updatemonth")
	public void updatemonth() throws Exception {
		System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSS");
	}

	// @Action("/system/treport/list/compositor")
	// public String compositor() throws Exception {
	//
	// String hqlSentence = "FROM PurchaseOrder purchaseorder WHERE 1 = 1 ";
	//
	// searchComponent.resetOrderSentence();
	//
	// searchComponent.addSearchElement("orderBy.purchaseorder.orderDate",
	// "DESC");
	// searchComponent.addSearchElement("orderBy.purchaseorder.id", "ASC");
	// Result result = purchaseOrderService.searchByPage(hqlSentence,
	// searchComponent, page);
	// purchaseOrders = result.getItems();
	// page = result.getPage();
	// return "index";
	// }

	// @Action("/system/treport/list/redcompositor")
	// public String redCompositor() throws Exception {
	//
	// String hqlSentence = "FROM PurchaseOrder purchaseorder WHERE 1 = 1 ";
	//
	// searchComponent.resetOrderSentence();
	// searchComponent.addSearchElement("orderBy.purchaseorder.percentage",
	// "ASC");
	// searchComponent.addSearchElement("orderBy.purchaseorder.orderDate",
	// "DESC");
	// Result result = purchaseOrderService.searchByPage(hqlSentence,
	// searchComponent, page);
	// purchaseOrders = result.getItems();
	// page = result.getPage();
	// return "index";
	// }

	@Override
	public void resetCustomerSearchCriteria() {

	}

	public List<Treport> getTreport() {
		return treport;
	}

	public void setTreport(List<Treport> treport) {
		this.treport = treport;
	}

	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}

}
